﻿// This code is released under the BSD license.
namespace PugLib.Functional
{
    using System;
    using System.Collections.Generic;

    public static class MapReduce
    {
        public static List<T> Map<T>(Func<T, T> function, IList<T> input)
        {
            List<T> rtn = new List<T>(input.Count);
            for (int i = 0; i < input.Count; i++)
            {
                rtn[i] = function(input[i]);
            }
            return rtn;
        }

        public static T Reduce<T>(Func<T, T, T> fn, T[] a, T init)
        {
            T s = init;
            for (int i = 0; i < a.Length; i++)
            {
                s = fn(s, a[i]);
            }
            return s;
        }

        public static int Sum(int[] arr)
        {
            return Reduce((a, b) => a + b, arr, 0);
        }

        public static string Join(string[] arr)
        {
            return Reduce((a, b) => a + b, arr, string.Empty);
        }
    }
}